<?php
class Vistec_Lightspeed_Model_Observer
{
public function checkComparelog($observer)
{
$checkout = $observer->getData('type_onepage');
$_order = new Mage_Sales_Model_Order();
$incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$_order->loadByIncrementId($incrementId);
//create an order
$_order->getShippingAddress()->getFirstname(); 
$_order->getShippingAddress()->getLastname(); 
$_order->getShippingAddress()->getCompany(); 
$_order->getShippingAddress()->getStreet(); 
$_order->getShippingAddress()->getRegion(); 
$_order->getShippingAddress()->getCity(); 
$_order->getShippingAddress()->getPostcode(); 
$_order->getShippingAddress()->getCountry_id(); 

//process the items
$items=array();
$i=0;
foreach($_order->getAllItems() as $item)
{
	$arr=array();
	$array['sku']=$item->getData('sku');	
	$array['row_total']=$item->getData('row_total')+$item->getData('tax_amount');
	$array['qty']=$item->getData('qty_ordered');
	$array['price']=$item->getData('price')+($item->getData('tax_amount')/$array['qty']);
	//get all the other info too
	$items[]=$array;
}
//Mage::log("New Order {$items} is the billing address");
//$sql = "SELECT * FROM xlsws_product as Product";
//$read = Mage::getSingleton('core/resource')->getConnection('lsremote_read')->fetchAll($sql);

$sql="SELECT MAX(SUBSTRING(`id_str` FROM 4)) as 'id_str' FROM  xlsws_cart";
$results = Mage::getSingleton('core/resource')->getConnection('lsremote_read')->fetchAll($sql);
if(count($results)>0)	{
$orderId=$results[0]['id_str']+1;
$id_str="WO-".$orderId;
} else {
$id_str="WO-12000";
}
//create an order in lightspeed
//create an order in lightspeed
$arrFields=array();
$arrFields["id_str"]=$id_str;
$arrFields["address_bill"] = $_order->getBillingAddress()->getName(); 
$arrFields["address_ship"] = $_order->getShippingAddress()->getName(); 
$arrFields["ship_firstname"] = $_order->getShippingAddress()->getFirstname(); 
$arrFields["ship_lastname"] = $_order->getShippingAddress()->getLastname(); 
$arrFields["ship_company"] = $_order->getShippingAddress()->getCompany();
$arrFields["ship_address1"] = implode(", ",$_order->getShippingAddress()->getStreet());
$arrFields["ship_address2"] = $_order->getShippingAddress()->getRegion(); 
$arrFields["ship_city"] = $_order->getShippingAddress()->getCity(); 
$arrFields["ship_zip"] = $_order->getShippingAddress()->getPostcode();
$arrFields["zipcode"] = $_order->getShippingAddress()->getPostcode(); 
$arrFields["ship_country"] = $_order->getShippingAddress()->getCountry_id(); 
$arrFields["contact"] = $_order->getBillingAddress()->getName(); 
//$arrFields["discount"];
$arrFields["firstname"] = $_order->getShippingAddress()->getFirstname(); 
$arrFields["lastname"] = $_order->getShippingAddress()->getLastname(); 
$arrFields["company"] = $_order->getShippingAddress()->getCompany();
$arrFields["name"] = $_order->getBillingAddress()->getName(); 
$arrFields["phone"] = $_order->getBillingAddress()->getTelephone();
$arrFields["ship_phone"] = $_order->getBillingAddress()->getTelephone(); 
//$arrFields["po"]; //blank
$arrFields["type"] = 4;
$arrFields["status"] = "Awaiting Processing";
//$arrFields["cost_total"]; //blank
$arrFields["currency"] = "USD";
//$string.=" , currency_rate"];//blank
$arrFields["datetime_cre"] = date('Y-m-d H:i:s', time());
$arrFields["datetime_due"] = date('Y-m-d H:i:s', time());
//$arrFields["datetime_posted"]; $_order->
$arrFields["email"] = $_order->getCustomerEmail();
//$arrFields["sell_total"];//blank
//$arrFields["printed_notes"];//blank
$arrFields["shipping_method"] = "SHIPPING";
$arrFields["shipping_module"] = "store_pickup.php"; // flat_rate.php for flat rate delivery or store_pickup.php for pickup
$arrFields["shipping_data"] = "Store Pickup"; //"Home Delivery Service or Store Pickup from our store"
$arrFields["shipping_cost"] = $_order->getShippingAmount()+$_order->getShippingTaxAmount();
$arrFields["shipping_sell"] = $_order->getShippingAmount()+$_order->getShippingTaxAmount();
$arrFields["payment_method"] = "Cash"; //Cash or Credit Card
$arrFields["payment_module"] = "phone_order.php";//phone_order.php, paypal.php
$arrFields["payment_data"] = "Phone Order";//"Phone Order for Pickup, Tel, etc, or UT# from paypal google etc for credit c ard"
$arrFields["payment_amount"]= $_order->getTotalPaid();//0 for pickup tel etc, amount for credit card, google, paypal etc.
$arrFields["fk_tax_code_id"] = 0; //0
$arrFields["tax_inclusive"] = 1; //1
$arrFields["subtotal"] = $_order->getBaseSubtotal()+$_order->getTaxAmount()-$_order->getShippingTaxAmount(); //tax inclusive total
$arrFields["tax1"]=0;//0
$arrFields["tax2"]=$_order->getTaxAmount();//VAT amount to 12 Decimal places
$arrFields["tax3"]=0;//0
$arrFields["tax4"]=0;//0
$arrFields["tax5"]=0;//0
$arrFields["total"]=$_order->getGrandTotal();//total shipping, and subtotal
$arrFields["count"]=count($items);//no of items
$arrFields["downloaded"]=0;//0
//$arrFields["user"];//null
$arrFields["ip_host"]=$_order->getRemoteIP();//host or ip address of customer
//$arrFields["customer_id"];//leave for now
//$arrFields["gift_registry"];//null
//$arrFields["send_to"];
$arrFields["submitted"]=date('Y-m-d H:i:s', time());
$arrFields["modified"]=date('Y-m-d H:i:s', time());
//$arrFields["linkid"]=""; //UUID

$arrFieldNames=(array_keys($arrFields));
$strFields = "(".implode(", ",$arrFieldNames).",linkid)";
$strValues = "('".implode("', '",$arrFields)."',UUID())";
$strInsertQuery="INSERT INTO xlsws_cart ".$strFields." VALUES ".$strValues;

$insert = Mage::getSingleton('core/resource')->getConnection('lsremote_read')->raw_query($strInsertQuery);


$cartId = Mage::getSingleton('core/resource')->getConnection('lsremote_read')->lastInsertId();

foreach($items as $item)	{
	

	$sql = "SELECT * FROM xlsws_product as Product WHERE code LIKE '".$item['sku']."'";
	$arrResult = Mage::getSingleton('core/resource')->getConnection('lsremote_read')->fetchAll($sql);

	
	if(count($arrResult)>0)
	{
		$product=$arrResult[0];
		$date=date('Y-m-d H:i:s', time());
		//add item to cart
		$strInsertQuery = "INSERT INTO xlsws_cart_item
   (`cart_id`, `cart_type`, `product_id`, `code`, `description`, `discount`, `qty`, `sell`, `sell_base`, `sell_discount`, `sell_total`, `serial_numbers`, `gift_registry_item`, `datetime_added`, `datetime_mod`)
VALUES
   ('{$cartId}', 1, '{$product['rowid']}', '{$product['code']}', '{$product['description_short']}', '', '{$item['qty']}', {$item['price']}, {$item['price']}, 0, {$item['row_total']}, NULL, 0, '{$date}', '{$date}')";
   			
		$insert = Mage::getSingleton('core/resource')->getConnection('lsremote_read')->raw_query($strInsertQuery);
		Mage::log("New Order {$items} is the billing address");
		
	}
	
	
}







//get items and foreach item create a line item in lightspeed database

}
}